package top.codecrab.semaphore;

import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;

/**
 * @author codecrab
 * @since 2021年07月01日 8:27
 */
public class SemaphoreDemo {
    public static void main(String[] args) {
        //信号量：模拟五台手机准备被抢购
        Semaphore semaphore = new Semaphore(5);

        //十个线程，模拟十个用户抢手机
        for (int i = 1; i <= 10; i++) {
            new Thread(() -> {
                try {
                    semaphore.acquire();
                    System.out.println(Thread.currentThread().getName() + "号抢到手机，未付款");
                    TimeUnit.SECONDS.sleep(3);
                    System.out.println(Thread.currentThread().getName() + "号取消订单");
                } catch (InterruptedException e) {
                    e.printStackTrace();
                } finally {
                    semaphore.release();
                }
            }, String.valueOf(i)).start();
        }

    }
}
